package com.example.wjh.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.wjh.entity.News;
import com.example.wjh.mapper.NewsMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@CrossOrigin
@RestController
@RequestMapping("/news")
public class NewsController {

    @Autowired
    private NewsMapper newsMapper;

    // 获取最新的三条资讯名称
    @GetMapping("/latest")
    public List<News> getLatestNews() {
        return newsMapper.findLatestNews();
    }

    // 添加新资讯
    @PostMapping("/add")
    public String addNews(@RequestBody News news) {
        int rows = newsMapper.insert(news);
        return rows > 0 ? "资讯添加成功" : "资讯添加失败";
    }

    // 更新资讯信息
    @PutMapping("/update/{id}")
    public String updateNews(@PathVariable Long id, @RequestBody News news) {
        news.setId(id);  // 设置资讯ID
        int rows = newsMapper.updateById(news);
        return rows > 0 ? "资讯更新成功" : "资讯更新失败";
    }

    // 删除指定 ID 的资讯
    @DeleteMapping("/delete/{id}")
    public String deleteNews(@PathVariable Long id) {
        int rows = newsMapper.deleteById(id);
        return rows > 0 ? "资讯删除成功" : "资讯删除失败";
    }

    // 获取所有资讯信息
    @GetMapping("/all")
    public List<News> getAllNews() {
        return newsMapper.selectList(null);
    }

    // 根据ID获取资讯信息
    @GetMapping("/{id}")
    public News getNewsById(@PathVariable Long id) {
        return newsMapper.selectById(id);
    }

    // 分页获取资讯信息
    @GetMapping("/page")
    public IPage<News> getNewsPage(@RequestParam("pageNum") Integer pageNum,
                                   @RequestParam("pageSize") Integer pageSize) {
        Page<News> page = new Page<>(pageNum, pageSize);
        return newsMapper.selectPage(page, null);
    }

    // 多条件查询资讯信息
    @GetMapping("/search")
    public List<News> searchNews(@RequestParam(required = false) String publisherName,
                                 @RequestParam(required = false) String newsName,
                                 @RequestParam(required = false) String newsSource) {
        QueryWrapper<News> queryWrapper = new QueryWrapper<>();
        queryWrapper.like(publisherName != null, "publisherName", publisherName)
                .like(newsName != null, "newsName", newsName)
                .like(newsSource != null, "newsSource", newsSource);
        return newsMapper.selectList(queryWrapper);
    }

    // 批量删除资讯
    @DeleteMapping("/delete/batch")
    public int deleteBatch(@RequestBody List<Long> ids) {
        return newsMapper.deleteBatchIds(ids);
    }
}
